package com.javaclimb.controller;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.javaclimb.pojo.SelectTree;
import com.javaclimb.utils.PageBean;
import com.javaclimb.utils.Result;
import com.javaclimb.pojo.Tree;
import com.javaclimb.service.TreeService;
import com.javaclimb.utils.Consts;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Slf4j //用于记录日志
@RestController
@RequestMapping("/tree")//共同路径
public class TreeController {

    @Autowired
    private TreeService treeService;

    @GetMapping("/getTrees")
    public Object getAllTree(HttpServletRequest request) {
        JSONObject jsonObject = new JSONObject();
        List<Tree> trees = treeService.getAllTrees();
        if (trees == null) {
            jsonObject.put(Consts.MSG, "暂无古树信息");
            return jsonObject;
        } else {
            return trees;
        }
    }

    /**
     * 分页查询古树信息，路径传参
     *
     * @param currentPage
     * @param pageSize
     * @return
     */
    @GetMapping("{currentPage}/{pageSize}")
    public Object getTreeByPage(@PathVariable Integer currentPage,
                                @PathVariable Integer pageSize) {
        JSONObject jsonObject = new JSONObject();
        PageHelper.startPage(currentPage, pageSize);

        List<Tree> treeList = treeService.getAllTrees();

        PageInfo<Tree> treePageInfo = new PageInfo<>(treeList);

        if (treePageInfo.getList() != null) {
            return treePageInfo;
        } else {
            jsonObject.put(Consts.CODE, 0);
            jsonObject.put(Consts.MSG, "暂无数据");
            return jsonObject;
        }
    }

    /**
     * String code,String city,String district,String level,String fa
     */
    @GetMapping("")
    public Object getTreeByKeys(HttpServletRequest request) {
        JSONObject jsonObject = new JSONObject();
        String pageSize = request.getParameter("pageSize");
        String currentPage = request.getParameter("currentPage");

        String code = request.getParameter("code").trim();
        String city = request.getParameter("city");
        String district = request.getParameter("district");
        String level = request.getParameter("level");
        String family = request.getParameter("family");
        String genus = request.getParameter("genus");

        System.out.println("pageSize=" + pageSize);
        System.out.println("currentPage=" + currentPage);
        System.out.println("code=" + code);
        System.out.println("city=" + city);
        System.out.println("district=" + district);
        System.out.println("level=" + level);
        System.out.println("family=" + family);
        System.out.println("genus=" + genus);

        Tree tree = new Tree();
        if (!code.equals("") && !code.equals("undefined"))
            tree.setCode("%" + code + "%");
        if (!city.equals("") && !city.equals("undefined"))
            tree.setCity(city);
        if (!district.equals("") && !district.equals("undefined"))
            tree.setDistrict(district);
        if (!level.equals("") && !level.equals("undefined"))
            tree.setLevel(level);
        if (!family.equals("") && !family.equals("undefined"))
            tree.setFamily(family);
        if (!genus.equals("") && !genus.equals("undefined"))
            tree.setGenus(genus);

        PageHelper.startPage(Integer.parseInt(currentPage), Integer.parseInt(pageSize));

        List<Tree> treeList = treeService.queryByKeys(tree);

        PageInfo<Tree> treePageInfo = new PageInfo<>(treeList);

        if (treePageInfo.getList() != null || !treeList.isEmpty()) {
            return treePageInfo;
        } else {
            jsonObject.put(Consts.CODE, 0);
            jsonObject.put(Consts.MSG, "暂无数据");
            return jsonObject;
        }
    }

    //参数查看接口文档来命名
    @PostMapping(value = "/selectTree")
    public Result page(@RequestBody SelectTree st){
        Integer page = st.getPage();
        Integer pageSize = st.getPageSize();
        //log.info("分页查询，参数：{}，{}，{}",page,pageSize,st);
        //调用service分页查序
        PageBean pB = treeService.page(page,pageSize,st);
        return Result.success(pB);
    }

    //批量删除
    @DeleteMapping("/{ids}")//传递地址参数
    public Result delete(@PathVariable List<Integer> ids){
        log.info("批量删除操作，ids:{}",ids);
        treeService.delete(ids);
        return Result.success();
    }

    //新增古树
    //参数不需要提供city和district，服务层已抽取地址实现
    @PostMapping("/addTree")
    public Result save(@RequestBody Tree tree) {
        log.info("新增古树，tree:{}", tree);
        treeService.save(tree);
        return Result.success();
    }

    //修改古树，分两步
    //1、查询回显、查询单个古树信息
    @GetMapping("/{id}")
    public Result getById(@PathVariable Integer id) {
        log.info("根据id查询古树信息：{}", id);
        Tree tree = treeService.getById(id);
        return Result.success(tree);
    }

    //2、修改古树
    @PutMapping("/updateTree")
    public Result update(@RequestBody Tree tree) {
        log.info("更新古树信息：{}", tree);
        log.info("更新古树年龄：{}", tree.getEstimateAge());
        treeService.update(tree);
        return Result.success();
    }

    /**
     * 点赞
     */
    @PostMapping("/addLike")
    public Object addLike(HttpServletRequest request) {
        JSONObject jsonObject = new JSONObject();
        String id = request.getParameter("id").trim();
        boolean flag = treeService.addLike(Integer.parseInt(id));
        if (flag) {
            jsonObject.put(Consts.CODE, 1);
            return jsonObject;
        } else {
            jsonObject.put(Consts.CODE, 0);
            return jsonObject;
        }
    }

    /**
     * 获取点赞数量
     */
    @GetMapping("getLike")
    public Object getLike(HttpServletRequest request) {
        JSONObject jsonObject = new JSONObject();
        String id = request.getParameter("id").trim();
        Integer nums = treeService.getLike(Integer.parseInt(id));
        jsonObject.put("like", nums);
        return jsonObject;
    }

    /**
     * 获取访问量前十的古树
     */
    @GetMapping("/getHotTree")
    public Object getHotTree() {
        List<Tree> trees = treeService.selectHotTreeTopTen();
        return trees;
    }

    /**
     * 根据古树id增加访问量，同一个用户可重复
     */
    @PostMapping("/addVisit")
    public Object addVisit(HttpServletRequest request) {
        JSONObject jsonObject = new JSONObject();
        String id = request.getParameter("id").trim();
        boolean flag = treeService.addVisitById(Integer.parseInt(id));
        if (flag) {
            jsonObject.put(Consts.CODE, 1);
            return jsonObject;
        } else {
            jsonObject.put(Consts.CODE, 0);
            return jsonObject;
        }
    }

    /**
     * 根据古树id查询访问量
     */
    @GetMapping("/getVisitById")
    public Object getVisitById(HttpServletRequest request) {
        JSONObject jsonObject = new JSONObject();
        String id = request.getParameter("id").trim();
        Integer visits = treeService.queryVisitsById(Integer.parseInt(id));
        jsonObject.put("visits", visits);
        return jsonObject;
    }

    /**
     * 根据古树名称，地址模糊查询
     */
    @GetMapping("/getTreeByInput")
    public Object getTreeByInput(HttpServletRequest request) {
        JSONObject jsonObject = new JSONObject();
        String q = request.getParameter("q");
        List<Tree> trees = treeService.getTreeByInput("%" + q + "%");
        return trees;
    }

}
